package com.upload.service.impl;

import com.upload.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public void uploadFile(MultipartFile file, String path) throws IOException {
        int num = 0;
        File newFile = new File(path + File.separator + file.getOriginalFilename());
        while (newFile.exists()){
            String s = path + File.separator + (file.getOriginalFilename().contains(".") ? file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) : file.getOriginalFilename()) + (num == 0 ? "" :" (" + num + ")") + (file.getOriginalFilename().contains(".") ? file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")) : "");
            newFile = new File(s);
        }
        file.transferTo(newFile);
    }
}
